package com.topisv.tms.web.send;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.LogisticsCompany;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.send.ExpressCompanyMap;
import com.topisv.tms.entity.send.SendOut;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.send.SendOutDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.send.SendOutService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.tools.ExcelUtils2;
import com.topisv.tms.tools.MultiDataSourceExcelStUtil;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.TopUtils;
import com.topisv.tms.utils.enums.DataTableEnums;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.rule.TMSTransportRule;
import com.topisv.tms.web.base.BaseController;

import jxl.write.WritableSheet;
import net.sf.json.JSONObject;

/**
 * 快递交接的Controller, 使用Restful风格的Urls:
 * 
 * @author Arthur
 */

@Controller
@RequestMapping(value = "/sendout")
public class SendOutController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger("SendOutController.class");  
	
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	
	@Autowired
	private CustomersService customersService;
	
	@Autowired
	private AreaGroupService areaGroupService;
	
	@Autowired
	private WorkOrderService workOrderService;
	
	@Autowired
	private SendOutService sendOutService;
	
	@RequestMapping(value = "v2_init")
	public String init(Model model){
		List<LogisticsCompany> cmpList = logisticsCompanyService.findAll();
		model.addAttribute("cmpList",cmpList);
		fillSelectValue(model,null);
		return "send/sendout";
	}
	
	
	@SuppressWarnings("unused")
	@RequestMapping(value = "send2")
	public void send2(ServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		ShiroUser user = getShiroUser();
		String msg = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String logistic = request.getParameter("logistic");
			String warehouseCode = request.getParameter("warehouseCode");
			
			//add 装车流水号  bug530 by zhangweize 
			String sendCode = request.getParameter("sendCodeTemp");
			
			logger.info("send2--快递单号:" + logistic);
			SendOut send = sendOutService.findByLogisticNumber(logistic);
			if (null != send) {
				msg = "repeat";
			} else {
				WorkOrder workOrder = this.workOrderService.loadByExpressNoAndWarehouseCode(logistic, warehouseCode);
				if (null == workOrder) {
					msg = "work error";
				} else if (!workOrder.getWarehouseCode().equals(warehouseCode)) {
					msg = "warehouse error";
				} else {
					
					//begin add bug530 by zhangweize 
					if (!"".equals(sendCode)) {
						List<SendOut> list = sendOutService.findBySendCode(sendCode);
						if (list != null && !list.isEmpty()) {
							if (!list.get(0).getLogisticCompany().equals(workOrder.getExpressCompany())) {
								throw new RuntimeException("快递公司不一致!");
							}
						} else {
							throw new RuntimeException("该流水号所关联的快递单号为空!");
						}
					}
					//end add bug530 by zhangweize 
					
					SendOut sendOut = new SendOut();
					sendOut.setLogisticNumber(logistic);
					sendOut.setLogisticCompany(workOrder.getExpressCompany());
					sendOut.setCustomerCode(workOrder.getCustomerCode());
					sendOut.setWarehouseCode(workOrder.getWarehouseCode());
					sendOut.setSendTime(new Date());
					sendOut.setCreationDate(new Date());
					sendOut.setLastUpdateTime(new Date());
					sendOut.setCreatedBy(Integer.valueOf(user.id.toString()));
					sendOut.setLastUpdatedBy(Integer.valueOf(user.id.toString()));
					
					//add 装车流水号  bug530 by zhangweize 
					sendOut.setSendCode("".equals(sendCode) ? TMSTransportRule.generateSendOutCode() : sendCode);
					
					String sendTime = DateUtils.format(sendOut.getSendTime(), "yyyy-MM-dd HH:mm:ss");
					String expressCompany = logisticsCompanyService.getLogisticsCompanyByCode(sendOut.getLogisticCompany()).getCompanyName();
					if (sendOut != null) {
						sendOutService.save(sendOut);
						String customer = customersService.findByCustomerCode(sendOut.getCustomerCode())
								.getCustomerName();
						String warehouse = areaGroupService.findByGroupCode(sendOut.getWarehouseCode()).getGroupName();
						json.put("sendOut", sendOut);
						json.put("sendTime", sendTime);
						json.put("expressCompany", expressCompany);
						json.put("customer", customer);
						json.put("warehouse", warehouse);
						msg = "success";
					} else {
						msg = "error";
					}
				}
			}
			json.put("msg", msg);
			out.print(json);
		} catch (Exception e) {
			logger.error("send2--error", e);
			json.put("msg", "excetpion error");
			json.put("content", e.getMessage());
			out.print(json);
		}

	}
	
	/*
	 * 保存快递交接信息
	 * 验证信息：1、重复扫描
	 *        2、无法获取对应工单号
	 
	@RequestMapping(value = "send")
	public void send(ServletRequest request,HttpServletResponse response){
		PrintWriter out=null;
		JSONObject json=null;
		ShiroUser user = getShiroUser();
		String msg = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String logistic=request.getParameter("logistic");
			String warehouseCode=request.getParameter("warehouseCode");
			logger.info("快递单号:" + logistic);
			SendOut send = sendOutService.findByLogisticNumber(logistic);
			if(send != null){
				msg = "repeat";
			}else{
			WorkOrder workOrder=this.workOrderService.loadByExpressNo2(logistic);
			if(workOrder == null){
				msg="work error";
			}else{
			 if(!workOrder.getWarehouseCode().equals(warehouseCode)){
				msg="warehouse error";
			 }else
			 {
				SendOut sendOut = new SendOut();
				sendOut.setLogisticNumber(logistic);
				sendOut.setLogisticCompany(workOrder.getExpressCompany());
				sendOut.setCustomerCode(workOrder.getCustomerCode());
				sendOut.setWarehouseCode(workOrder.getWarehouseCode());
				sendOut.setSendTime(new Date());
				sendOut.setCreationDate(new Date());
				sendOut.setLastUpdateTime(new Date());
				sendOut.setCreatedBy(Integer.valueOf(user.id.toString()));
				sendOut.setLastUpdatedBy(Integer.valueOf(user.id.toString()));
				String sendTime = DateUtils.format(sendOut.getSendTime(), "yyyy-MM-dd HH:mm:ss");
				String expressCompany = logisticsCompanyService.getLogisticsCompanyByCode(sendOut.getLogisticCompany()).getCompanyName();
				if(sendOut != null){
				   sendOutService.save(sendOut);
				   String customer = customersService.findByCustomerCode(sendOut.getCustomerCode()).getCustomerName();
				   String warehouse = areaGroupService.findByGroupCode(sendOut.getWarehouseCode()).getGroupName();
				   json.put("sendOut", sendOut);
				   json.put("sendTime",sendTime);
				   json.put("expressCompany", expressCompany);
				   json.put("customer", customer);
				   json.put("warehouse", warehouse);
				   msg="success";
				}else{
				   msg="error";
				}
			  }
			  }
			 }
			
			//获取当日快递交接结果
			try{
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date fromDate = sdf2.parse(sdf.format(new Date()) + " 00:00:00");
			    Date toDate = sdf2.parse(sdf.format(new Date()) + " 23:59:59");
				List<SendOut> sendOutList = sendOutService.getTodaySendOut(warehouseCode,new java.sql.Date(fromDate.getTime()),new java.sql.Date(toDate.getTime()));
				
				Map<SendOutSum,Integer> sumList = new HashMap<SendOutSum, Integer>();
				for(SendOut sendOut:sendOutList){
					SendOutSum sendOutSum = new SendOutSum(sendOut.getCustomer().getCustomerName(),
														   sendOut.getWarehouse().getGroupName(),
														   sendOut.getCompany().getCompanyName());
					if(sumList.size() == 0){
						sumList.put(sendOutSum, 1);
					}else{
					for(SendOutSum entry:sumList.keySet()){
						if(entry.getCustomer() == sendOutSum.getCustomer() &&
						   entry.getWarehouse() == sendOutSum.getWarehouse() &&
						   entry.getCompany() == sendOutSum.getCompany()){
						   sumList.put(entry, sumList.get(entry) + 1);
						}else{
							sumList.put(sendOutSum, 1);
						}
					  }
					}
				};
				for(SendOutSum entry:sumList.keySet()){
					logger.info(entry.customer + " " + entry.warehouse + " " + entry.company + " "+ sumList.get(entry));
				}
				json.put("sendOutList",sumList);
			}catch(Exception e){
				e.printStackTrace();
			}
			json.put("msg", msg);
			out.print(json);
			} catch (Exception e) {
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}	
	}*/
	
	
	/*
	 * 保存快递公司与快递单号对应关系
	 */
	/*private Map<String,String> getLogisticMap(){
		Map<String,String> logisticMap = new HashMap<String,String>();
		logisticMap.put("50", "EMS");
		logisticMap.put("95", "EMS");
		logisticMap.put("VB", "JD");
		logisticMap.put("22", "STO");
		logisticMap.put("33", "STO");
		logisticMap.put("56", "STO");
		logisticMap.put("55", "TTKDEX");
		logisticMap.put("58", "TTKDEX");
		logisticMap.put("99", "TTKDEX");
		logisticMap.put("40", "ZTO");
		logisticMap.put("53", "ZTO");
		logisticMap.put("76", "ZTO");
		logisticMap.put("80", "YTO");
		return logisticMap;
	}
	*/
	/**
	 * 
	 * @param logistic
	 * @param expressCode
	 */
	private boolean checkLogistic(String logistic,String expressCode){
		boolean flag;
		String express = null;
		Map<String,String> logisticMap = ExpressCompanyMap.getMap();//getLogisticMap();
		
		for(String s:logisticMap.keySet()){
			if(logistic.startsWith(s)){
				express = logisticMap.get(s);
				break;
			}
		}
		
		if(express.equals(expressCode))
		{
			flag = true;
		}else{
			flag = false;
		}
		
		return flag;
		/*String map = logistic.substring(0,2);
		boolean isNum = map.matches("[0-9]+");
		if(!isNum){
			String express = logisticMap.get(map);
			if(express.equals(expressCode)){
				flag = true;
			}
			else{
				flag = false;
			}
		}else{
		   String map2 = logistic.substring(0,3);
		   String express = logisticMap.get(map2);
		   if(express.equals(expressCode)){
			   flag = true;
		   }else{
			   flag = false;
		   }
		}
		return flag;*/
	}
	
	/*
	 * 保存快递交接信息
	 * 验证信息：1、重复扫描
	 *        2、无法获取对应工单号
	 */
	@RequestMapping(value = "send")
	public void send(ServletRequest request,HttpServletResponse response){
		PrintWriter out=null;
		JSONObject json=null;
		ShiroUser user = getShiroUser();
		String msg = null;
		
		try {
			out = response.getWriter();
			json = new JSONObject();
			String logistic=request.getParameter("logistic");
			String warehouseCode=request.getParameter("warehouseCode");
			String expressCode=request.getParameter("expressCompany");
			
			//add 装车流水号  bug530 by zhangweize 
			String sendCode =request.getParameter("sendCodeTemp");
			
			logger.info("快递交接快递单号:" + logistic);
			
			//判断快递单是否重复
			SendOut send = sendOutService.findByLogisticNumber(logistic);
			if(send != null){
				msg = "repeat";
			}else{
				boolean flag = checkLogistic(logistic,expressCode);
				if(!flag){
				   msg="expressCompany error";
				}else{
				   SendOut sendOut = new SendOut();
				   sendOut.setLogisticNumber(logistic);
				   sendOut.setLogisticCompany(expressCode);
				   sendOut.setWarehouseCode(warehouseCode);
				   sendOut.setSendTime(new Date());
				   sendOut.setCreationDate(new Date());
				   sendOut.setLastUpdateTime(new Date());
				   sendOut.setCreatedBy(Integer.valueOf(user.id.toString()));
				   sendOut.setLastUpdatedBy(Integer.valueOf(user.id.toString()));
				   
				 //add 装车流水号  bug530 by zhangweize 
				   sendOut.setSendCode( "".equals(sendCode) ? TMSTransportRule.generateSendOutCode() : sendCode);
				   
				   if(sendOut != null){
					   String sendTime = DateUtils.format(sendOut.getSendTime(), "yyyy-MM-dd HH:mm:ss");
					   String expressCompany = logisticsCompanyService.getLogisticsCompanyByCode(sendOut.getLogisticCompany()).getCompanyName();
					   String warehouse = areaGroupService.findByGroupCode(sendOut.getWarehouseCode()).getGroupName();
					   sendOutService.save(sendOut);
					   json.put("sendOut", sendOut);
					   json.put("sendTime",sendTime);
					   json.put("expressCompany", expressCompany);
					   json.put("warehouse", warehouse);
					   msg="success";
				   }else{
					   msg="error"; 
				   }
				}
			  }
			json.put("msg", msg);
			out.print(json);
			} catch (Exception e) {
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}	
	}
	
	/**
	 * 根据快递交接编码查询快递列表
	 * 
	 *
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "ajaxPrintExpressList", method = RequestMethod.POST)
	public void ajaxPrintExpressList(ServletRequest request, ServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String sendCode = request.getParameter("sendCode");
			
			//根据流水号获取快递交接明细
			List<SendOut> sendOutList = sendOutService.findBySendCode(sendCode);
			
			//更新打印时间
			sendOutService.updateSendOutPrintTime(sendCode);
			
			json.put("status", "1");
			json.put("content", sendOutList);
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
		} finally {
			out.print(json.toString());
		}

	}
	
	@RequestMapping(value = "v2_query",method = RequestMethod.GET)
	public String queryInit(Model model, ServletRequest request, ServletResponse response) throws Exception{
		List<LogisticsCompany> cmpList = logisticsCompanyService.findAll();
		model.addAttribute("cmpList",cmpList);
		fillSelectValue(model,null);
		return "send/sendoutList";
	}
	
	@RequestMapping(value = "query")
	public void query(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) throws Exception{
		try {
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Map<String, Object> param = paramHolder.getSearchParams();
			String expressCompany = (String)param.get("expressCompany");
			String warehouse = (String)param.get("warehouseCode");
			String expressNo = (String)param.get("expressNo");
			String fromDateStr=(String)param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			
			//bug530 by zhangweize
			String sendCode = (String) param.get("sendCode");
			
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("expressCompany", expressCompany);
			param.put("warehouse", warehouse);
			param.put("expressNo", expressNo);
			
			//bug530 by zhangweize
			param.put("sendCode", sendCode);
			
			Page<SendOut> page = this.sendOutService.loadPageByParam(paramHolder.getSearchParams(),paramHolder.getCurPage(), paramHolder.getPageSize());
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			logger.error("error",e);
		}
	}
	
	@RequestMapping(value = "v2_toQuery")
	public String toUlorderMgrPagee(Model model, ServletRequest request) {
		try {
			List<LogisticsCompany> cmpList = logisticsCompanyService.findAll();
			model.addAttribute("cmpList",cmpList);
			fillSelectValue(model,null);
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "send/sendoutList";
	}
	
	public QueryParamHolder collectParam(JSONParam[] paramJson,String prefix){
		// 客户端参数
		Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
		int start = Integer.parseInt(paramMap.get(DataTableEnums.DISPLAY_START.getValue()));
		int pageSize = Integer.parseInt(paramMap.get(DataTableEnums.DISPLAY_LENGTH.getValue()));
		// 查询
		int curPage = (start / pageSize) + 1;
		Map<String, Object> searchParams = DataTablesUtils.getParametersStartingWith(paramMap, prefix);
		return new QueryParamHolder(start, pageSize, curPage, paramMap, TopUtils.cleanupMap2(searchParams));
	}
	
	/**
	 * 将查询结果封装为dataTable识别的json对象
	 * @param page
	 * @return JSONObject
	 */
	public <T> JSONObject bulidJSON(Page<T> page) {
		JSONObject json = new JSONObject();
		json.put(DataTableEnums.AA_DATA.getValue(), page.getContent());
		json.put(DataTableEnums.TOTAL_RECORED.getValue(), page.getTotalElements());
		json.put(DataTableEnums.TOTAL_RECORED_DISPLAY.getValue(), page.getTotalElements());
		return json;
	}
	
	
	/**
	 * 导出快递清单
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value = "exportExcel")
	public void outReturnExcel(ServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		String expressCompany = (String)searchParams.get("expressCompany");
		String warehouse = (String)searchParams.get("warehouseCode");
		String expressNo = (String)searchParams.get("expressNo");
		String fromTm = (String)searchParams.get("fromDate");
		String toTm = (String)searchParams.get("toDate");
		
		//bug530 by zhangweize
		String sendCode = (String) searchParams.get("sendCode");
		
		Date fromDate=null;
		Date toDate=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(StringUtils.isNotEmpty(fromTm)){
			fromDate=sdf.parse(fromTm+" 00:00:00");
		}
		if(StringUtils.isNotEmpty(toTm)){
			toDate=sdf.parse(toTm+" 23:59:59");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("expressCompany", expressCompany);
		param.put("warehouse", warehouse);
		param.put("expressNo", expressNo);
		param.put("fromDate", fromDate);
		param.put("toDate", toDate);
		
		param.put("sendCode", sendCode);
		
		List<SendOut> sendOutList = sendOutService.findSendOut(param);
		logger.info("=======开始导出快递清单=======");
		String filepath = "快递交接信息表.xls";
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition","attachment; filename=" + new String(filepath.getBytes("gb2312"),"iso8859-1"));

		Integer count = 0;
		Integer mapCount = 0;
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		String[] titles = {"交接时间","快递公司","快递单号","仓库","交接人"};
		String[] titles2 = {"快递公司","仓库","快递单数"};
		List<Object[]> rs = new ArrayList<Object[]>();
		List<Object[]> rs2 = new ArrayList<Object[]>();
		Map<SendOutSum,Integer> map = new ConcurrentHashMap<SendOutSum,Integer>();
		
		for(SendOut sendOut:sendOutList){
			mapCount = 0;
			SendOutSum sendOutSum = new SendOutSum(
					   sendOut.getWarehouse().getGroupName(),
					   sendOut.getCompany().getCompanyName());
			if(map.size() == 0){
				map.put(sendOutSum, 1);
			}else{
				for(SendOutSum entry:map.keySet()){
				 	if(entry.getWarehouse() == sendOutSum.getWarehouse() &&
							entry.getCompany() == sendOutSum.getCompany()){
				 	   map.put(entry, map.get(entry) + 1);
				 	   mapCount = 1;
					   break;
					}
				}
				
				if(mapCount == 0){
					map.put(sendOutSum, 1);
				}
					
			}
				    count += 1;
					Object[] object = {
							df.format(sendOut.getSendTime()),
							sendOut.getCompany().getCompanyName(),
							sendOut.getLogisticNumber(),
							sendOut.getWarehouse().getGroupName(),
							sendOut.getSender().getRealname(),
							null
					};
					rs.add(object);
		}
		
		for(Map.Entry<SendOutSum, Integer> entry: map.entrySet()){
			Object[] object = {
					entry.getKey().company,
					entry.getKey().warehouse,
					entry.getValue(),
					null
			};
			rs2.add(object);
		}
		Object[] object3 ={"总计",null,String.valueOf(count),null};
		rs2.add(object3);
		
		try{
			ExcelUtils2.getInstance(response.getOutputStream());
			WritableSheet sheet = ExcelUtils2.addSheet("明细",0);
			ExcelUtils2.writeSheet(sheet,titles,"快递清单明细表",rs);
			WritableSheet sheet2 = ExcelUtils2.addSheet("汇总",1);
			ExcelUtils2.writeSheet(sheet2,titles2,null,rs2);
			ExcelUtils2.closeWorkBook();
		
		}catch(Exception e){
			e.printStackTrace();
		}
        logger.info("=======导出结束=======");
	}
	
	
	/**
     * 导出快递清单（新），2016-06-12 重写 by lianghe.yuan
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "exportExcel")
    public void outReturnExcelNew(ServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");

        String expressCompany = (String) searchParams.get("expressCompany");
        String warehouse = (String) searchParams.get("warehouseCode");
        String expressNo = (String) searchParams.get("expressNo");
        String fromDateStr = (String) searchParams.get("fromDate");
        String toDateStr = (String) searchParams.get("toDate");
        
        if (StringUtils.isNotBlank(fromDateStr)) {
            fromDateStr += " 00:00:00";
        }
        if (StringUtils.isNotBlank(toDateStr)) {
            toDateStr += " 23:59:59";
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("expressCompany", expressCompany);
        param.put("warehouse", warehouse);
        param.put("expressNo", expressNo);
        param.put("fromDate", fromDateStr);
        param.put("toDate", toDateStr);

        //仓库条件处理 ， see SendOutService#getWhereClause(final Map<String, Object> param)
        if (StringUtils.isBlank(warehouse)) {
            ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
            List<AreaGroup> warehouseList = null;
            if (StatusEnums.user_type_customer.getStatus().equals(user.userType)) {
                warehouseList = areaGroupService.loadAreaGroupByAuthority(user, user.customerCode);
            } else if (StatusEnums.user_type_paiu.getStatus().equals(user.userType)) {
                warehouseList = areaGroupService.findByAreaGroups(user.areagroups);
            }
            
            List<String> whCodeList = new ArrayList<String>(warehouseList.size());
            for (AreaGroup ag : warehouseList) {
                whCodeList.add(ag.getGroupCode());
            }
            
            param.put("warehouseList", whCodeList);
        }
        
        //查询数据
        List<Object[]> sendOutList = sendOutService.findSendOutNew(param);
        
        //数据为空处理
        if (sendOutList == null || sendOutList.isEmpty()) {
            PrintWriter writer = response.getWriter();
            writer.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /></head>"
                    + "<body><script>alert('无符合条件的数据，请检查筛选条件!'); window.history.back();</script></body></html>");
            writer.flush();
            writer.close();
            
            return;
        }
        
        //汇总统计
        List<Object[]> countList = new ArrayList<Object[]>();
        
        Map<String, Integer> countMap = new HashMap<String, Integer>();
        for (Object[] sendOut : sendOutList) {
            String key = (String) sendOut[1] + "<-->" + (String) sendOut[3];
            Integer value = countMap.get(key);
            if (value == null)  value = 0; 

            countMap.put(key, value + 1);
        }
        
        for (Entry<String, Integer> entry : countMap.entrySet()) {
            String[] key = entry.getKey().split("<-->");
            Integer value = entry.getValue();
            
            Object[] countObj = new Object[3];
            countObj[0] = key[0];
            countObj[1] = key[1];
            countObj[2] = value;
            
            countList.add(countObj);
        }
        countList.add(new String[]{"总计", "", sendOutList.size() + ""});
        
        
        //导出Excel
        OutputStream os = null;
        
        try {
            response.setContentType("application/octet-stream");
            String fileName = new String(("快递交接信息表.xls").getBytes("GBK"), "ISO8859-1");
            ((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename=" + fileName);
            os = response.getOutputStream();

            List<String> multiSheetNamePreList = new ArrayList<String>(2);
            List<String> multiPageTitleList = new ArrayList<String>(2);
            List<String[]> multiTitleList = new ArrayList<String[]>(2);
            List<List<Object[]>> multiDataList = new ArrayList<List<Object[]>>(2);
            
            //第一类sheet：快递清单明细列表
            multiSheetNamePreList.add("明细");
            multiPageTitleList.add("快递清单明细列表");
            multiTitleList.add(new String[]{ "交接时间", "快递公司", "快递单号", "仓库", "交接人" });
            multiDataList.add(sendOutList);

            //第二类sheet：快递清单汇总
            multiSheetNamePreList.add("汇总");
            multiPageTitleList.add("快递清单汇总");
            multiTitleList.add(new String[]{ "快递公司", "仓库", "快递单数"});
            multiDataList.add(countList);
            
            //导出
            MultiDataSourceExcelStUtil.exportMulit(os, multiSheetNamePreList, multiPageTitleList, multiTitleList, multiDataList);
            
        } catch (Exception ex) {
            logger.error("导出快递交接信息表ERROR. ", ex);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("导出快递交接信息表关闭流异常. ", e);
                }
            }
        }
        
    }
	
	/**
	 * 自定义每日汇总类
	 * @author Administrator
	 *
	 */
	class SendOutSum{
		private String warehouse;
		private String company;
		
		public SendOutSum(String warehouse,String company){
			this.warehouse = warehouse;
			this.company = company;
		}
		
		public String getWarehouse() {
			return warehouse;
		}
		public void setWarehouse(String warehouse) {
			this.warehouse = warehouse;
		}
		public String getCompany() {
			return company;
		}
		public void setCompany(String company) {
			this.company = company;
		}
	}
}
